package cn.azzhu.day05;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author azzhu
 * @create 2020-09-19 19:33:17
 */
public class RestartStrategiesDemo {
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //只有开启了CheckPointing，才会有重启策略
        env.enableCheckpointing(5000);

        //默认的重启策略：固定延迟无限重启

        //指定重启策略，最多3次，每次间隔2s
        env.getConfig().setRestartStrategy(RestartStrategies.fixedDelayRestart(3,2000));

        final DataStreamSource<String> lines = env.socketTextStream("hadoop105", 9999);

//        final SingleOutputStreamOperator<String> toUpper = lines.map(new MapFunction<String, String>() {
//            @Override
//            public String map(String line) throws Exception {
//                if (line.startsWith("azzhu")) {
//                    throw new RuntimeException("程序挂了....");
//                }
//                return line.toUpperCase();
//            }
//        });
       // toUpper.print();

        final SingleOutputStreamOperator<Tuple2<String,Integer>> wordAndOne = lines.map(new MapFunction<String, Tuple2<String,Integer>>() {
            @Override
            public Tuple2<String,Integer> map(String line) throws Exception {
                if (line.startsWith("azzhu")) {
                    throw new RuntimeException("程序挂了....");
                }
                return Tuple2.of(line,1);
            }
        });

        final SingleOutputStreamOperator<Tuple2<String, Integer>> result = wordAndOne.keyBy(0).sum(1);

        result.print();

        env.execute("RestartStrategiesDemo");
    }
}
